package com.example.demo.common.converter;

import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author Shanks
 * @date 2020-10-30
 */
public class ConverterUtils {

    public static void copyProperties(Object source, Object target) {
        BeanUtils.copyProperties(source, target);
    }

    public static <T> T convert(Object source, Class<T> targetClass) {
        if (Objects.isNull(source)) {
            return null;
        }
        T t;
        try {
            t = targetClass.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            throw new RuntimeException("数据转换异常");
        }
        BeanUtils.copyProperties(source, t);
        return t;
    }

    public static <T> List<T> convert(List<?> sourceList, Class<T> targetClass) {
        if (CollectionUtils.isEmpty(sourceList)) {
            return Lists.newArrayList();
        }
        return sourceList.stream()
                .map(s -> {
                    T t;
                    try {
                        t = targetClass.newInstance();
                    } catch (InstantiationException | IllegalAccessException e) {
                        throw new RuntimeException("数据转换异常");
                    }
                    BeanUtils.copyProperties(s, Objects.requireNonNull(t));
                    return t;
                })
                .collect(Collectors.toList());
    }
}